/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Usuario;
import model.UsuarioDAO;

/**
 *
 * @author Eduarda
 */
public class TrataLogin extends Comando {

    @Override
    public void executar(HttpServletRequest request, HttpServletResponse response ) throws ClassNotFoundException, SQLException, IOException, ServletException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        String login = request.getParameter("Login");
        String senha = request.getParameter("Senha");

        UsuarioDAO dao = new UsuarioDAO();
        Usuario user = dao.pesquisarLogin(login);
         HttpSession session = request.getSession(true);
        session.setAttribute("identifica", user);
        
        if (user != null && user.getSenha().equals(senha)&& user.getTipoUsuario().getIdTipo()==1) {
            /*Cookie cookie = new Cookie("identifica", login);
             response.addCookie(cookie);*/
           

            //response.sendRedirect("index.jsp");
            out.println("<div class='bem-vindo'>Bem-vindo " + "<span>" + user.getLogin() + "</span>!</div>");
            RequestDispatcher rd = request.getRequestDispatcher("index_admin.jsp");
            rd.include(request, response);
        } else if (user != null && user.getSenha().equals(senha)&& user.getTipoUsuario().getIdTipo()==2) {
            
            out.println("<div class='bem-vindo'>Bem-vindo " + "<span>" + user.getLogin() + "</span>!</div>");
            RequestDispatcher rd = request.getRequestDispatcher("index_gerente.jsp");
            rd.include(request, response);
        }else if (user != null && user.getSenha().equals(senha)&& user.getTipoUsuario().getIdTipo()==3) {
            
            out.println("<div class='bem-vindo'>Bem-vindo " + "<span>" + user.getLogin() + "</span>!</div>");
            RequestDispatcher rd = request.getRequestDispatcher("index_secretaria.jsp");
            rd.include(request, response);
            
        }else if (user != null && user.getSenha().equals(senha)&& user.getTipoUsuario().getIdTipo()==4) {
            
            out.println("<div class='bem-vindo'>Bem-vindo " + "<span>" + user.getLogin() + "</span>!</div>");
            RequestDispatcher rd = request.getRequestDispatcher("index_medico.jsp");
            rd.include(request, response);
        }else {
            out.println("<h1> Ocorreu um erro durante o processo de autenticação </h1>");
            response.sendRedirect("index.jsp");
        }
        out.close();
    }
}
